class ArticleAdminController < ApplicationController
  layout 'main'
  after_filter :post_log
  
  def index
    @articles = Article.paginate :conditions =>["status=?","Y"], :per_page => 10, :page=>params[:page]
  end
  
  def new
    
  end
  
  def add_new
    article = Article.new(params[:article])
    if(params[:article][:filename]!=nil && params[:article][:filename]!='')
      filename = Article.save_file(params[:article][:filename])
      article.filename = filename
    end
    if(params[:article][:attachment]!=nil && params[:article][:attachment]!='')
      filename = Article.save_file(params[:article][:attachment])
      article.attachment = filename
    end
    article.user_id = session[:user_id]
    article.status = 'Y'
    article.save
    flash[:notice] = 'เพิ่มบทความเป็นที่เรียบร้อยแล้ว'
    redirect_to :action => 'index'
  end
  
  def edit
    @article = Article.find(params[:id])
  end
  
  def update
    #get old filename
    old_filename = Article.find(params[:article][:id]).filename
    old_attachment = Article.find(params[:article][:id]).attachment
    article = Article.update(params[:article][:id], params[:article])
    if(params[:article][:filename]!=nil && params[:article][:filename]!='')
      filename = Article.save_file(params[:article][:filename])
      article.filename = filename
    else
      article.filename = old_filename
    end
    if(params[:article][:attachment]!=nil && params[:article][:attachment]!='')
      filename = Article.save_file(params[:article][:attachment])
      article.attachment = filename
    else
      article.attachment = old_attachment
    end
    if(params[:del_file]!=nil)
	article.filename = nil
	file_name = "#{RAILS_ROOT}/public/files/"+old_filename
	File.delete(file_name) if File.exist?(file_name)
    end
    if(params[:del_attachment]!=nil)
	article.attachment = nil
	file_name = "#{RAILS_ROOT}/public/files/"+old_attachment
	File.delete(file_name) if File.exist?(file_name)
    end
    article.save
    flash[:notice] = 'แก้ไขบทความเป็นที่เรียบร้อยแล้ว'
    redirect_to :action => 'index'
  end
  
  def delete
    #Article.delete(params[:id])
    Article.update(params[:id], :status => 'D')
    flash[:notice] = 'ลบบทความเป็นที่เรียบร้อยแล้ว'
    redirect_to :action => 'index'
  end
end
